package edu.ynu.se.xiecheng.achitectureclass.common.service;


import edu.ynu.se.xiecheng.achitectureclass.common.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.common.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


@Service
public class UserService extends LogicService<UserDao, User, Long> {
    public UserService(@Autowired UserDao userDao) {
        super(userDao);
    }

    @Transactional
    public Boolean registerUser(User user) {
        if (user != null && user.getPassword() != null) {
            user.setPassword(this.hashPassword(user.getPassword()));
            return super.POST(user) != null;
        } else {
            throw new IllegalArgumentException("User or password cannot be null");
        }
    }

    @Transactional
    public Boolean loginUser(String userName, String password) {
        User user = (User)super.GET((long)Math.toIntExact(((UserDao)super.getDAO()).findUserByUserName(userName).getId()));
        return user == null ? false : this.hashPassword(password).equals(user.getPassword());
    }

    private String hashPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] encodedhash = digest.digest(password.getBytes());
            return this.bytesToHex(encodedhash);
        } catch (NoSuchAlgorithmException var4) {
            NoSuchAlgorithmException e = var4;
            throw new RuntimeException("Could not hash password", e);
        }
    }

    private String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);

        for(int i = 0; i < hash.length; ++i) {
            String hex = Integer.toHexString(255 & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }

            hexString.append(hex);
        }

        return hexString.toString();
    }
}
